import { observable, useStrict, action, runInAction, computed } from 'mobx'
import React from 'react'
import Loader from 'halogen/PulseLoader'
import { Link } from 'react-router-dom'
import $ from 'jquery'

useStrict(true)

class HeaderStore {
  @observable data = []
  @observable loading = true
  @observable error = null

  @action addRepo(repo) {
    this.data.push(repo)
  }

  @action loadHeaderData() {
    $.getJSON('/regional_design/repos.json').then(
      value => {
        runInAction("update state after fetching data", () => {
          this.data = value
          this.loading = false
        })
      },
      error => {
        runInAction("error", () => {
          this.error = error.statusText
          this.loading = false
        })
    })
  }

  @computed get showElements() {
    let result = null;

    if (this.loading) {
      result = <Loader color="#286090" size="12px" margin="4px"/>;
    }
    else if (this.error !== null) {
      result = <span>Error: {this.error}</span>;
    }
    else {
      const data = this.data.map((repo) => {
        const url = `/web/regional_design/${repo.id}?object=repo`
        return (
          <Link key={ repo.id } className='btn btn-default mr15' to={ url }>{ repo.name }</Link>
        )
      })

      result = data;
    }

    return result
  }
}

export default new HeaderStore()
